/*
 * topological-hex, a program to compute combinatorial hexahedral meshes.
 *
 * Copyright (C) <2018> <Université catholique de Louvain (UCL), Belgique>
 *
 * List of the contributors to the development, description and complete
 * License: see LICENSE file.
 *
 * This program (topological-hex) is free software:
 * you can redistribute it and/or modify it under the terms
 * of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program (see COPYING file).  If not,
 * see <http://www.gnu.org/licenses/>.
 */

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "server.h"
#include "compatibility.h"

typedef struct solution_data {
  FILE *file;
  pthread_mutex_t *lock;
  bool wrote_progress;
  double start_time;
} solution_data;

static
void on_solution(
  const char *user_name,
  const vertex_index *vertices, hex_index num_hexes,
  void *data);

static void on_debug_log(const char *message, void *data);
static void on_log(const char *message, void *data);
static void on_listen(void *data);
static void on_progress(uint32_t i, uint32_t n, void *data);
static void on_debug_progress(uint32_t i, uint32_t n, void *data);

static double get_time(void) {
#ifdef SET_GLIBC_LINK_VERSIONS_HEADER
  return time(NULL);
#else
  struct timespec time;
  clock_gettime(CLOCK_MONOTONIC, &time);
  return time.tv_sec + 1e-9 * time.tv_nsec;
#endif
}

int status;

static void parse_args(int *argc, char **argv,
                       const char **output_path,
                       const char **backup_path,
                       bool *try_restore,
                       bool *debug);

int main(int argc, char **argv) {
  int status = 0;

  const char *output_path, *backup_path;
  bool try_restore, debug;
  parse_args(&argc, argv, &output_path, &backup_path, &try_restore, &debug);

  server_backup_info backup = {backup_path, try_restore};

  FILE *output_file;
  if (output_path)
    output_file = fopen(output_path, "w");
  else
    output_file = stdout;

  if (!output_file) {
    status = 1;
    goto fail_open_file;
  }

  pthread_mutex_t lock;
  if (pthread_mutex_init(&lock, NULL) != 0) {
    status = 1;

    fprintf(stderr, "Failed to create lock!\n");
    goto fail_create_lock;
  }

  solution_data cb_data = {output_file, &lock, false, get_time()};

  if (server_run(on_solution, &cb_data,
                 debug ? on_debug_log : on_log, &lock,
                 on_listen, NULL,
                 debug ? on_debug_progress : on_progress, &cb_data,
                 backup_path ? &backup : NULL) != SUCCESS) {
    status = 1;
    fprintf(stderr, "Failed to run server!\n");
  }

  pthread_mutex_destroy(&lock);
fail_create_lock:
  if (output_path) fclose(output_file);
fail_open_file:
  return status;
}

static
void on_solution(const char *user_name,
                 const vertex_index *vertices, hex_index num_hexes,
                 void *data) {
  solution_data *cb_data = data;
  pthread_mutex_lock(cb_data->lock);

  fprintf(cb_data->file, "SOLUTION FOUND BY %s!\n", user_name);
  for (hex_index i = 0; i < num_hexes; i++) {
    fprintf(cb_data->file, "  %u) {", i);
    for (hex_vertex_index j = 0; j < 8; j++) {
      fprintf(cb_data->file, "%u", vertices[8*i+j]);
      if (j + 1 != 8) fprintf(cb_data->file, ", ");
    }
    fprintf(cb_data->file, "}\n");

    for (hex_index j = i+1; j < num_hexes; j++) {
      if (!hex_compatibility(vertices + 8*i, vertices + 8*j)) {
        fprintf(cb_data->file, "  ERROR: Hex #%u and #%u are incompatible!\n",
                i, j);
      }
    }
  }
  fflush(cb_data->file);

  pthread_mutex_unlock(cb_data->lock);
}

static
void on_log(const char *message, void *data) {}

static
void on_debug_log(const char *message, void *data) {
  pthread_mutex_t *lock = data;
  pthread_mutex_lock(lock);
  printf("%s\n", message);
  pthread_mutex_unlock(lock);
}

static void on_listen(void *data) {
}

#define BAR_WIDTH 50

static void on_debug_progress(uint32_t i, uint32_t n, void *data) {}

static void on_progress(uint32_t i, uint32_t n, void *data) {
  solution_data *args = data;

  FILE *out = stdout;

  pthread_mutex_lock(args->lock);
  if (!args->wrote_progress)
    fprintf(out, "\n");

  char bar[BAR_WIDTH + 1];
  uint64_t ticks = (BAR_WIDTH * (uint64_t)i) / n;
  memset(bar, '=', ticks);
  if (ticks != 0 && i != n) {
    bar[ticks - 1] = '>';
    memset(bar + ticks, ' ', BAR_WIDTH - ticks);
  }
  else if (ticks == 0)
    memset(bar + ticks, ' ', BAR_WIDTH - ticks);
  bar[BAR_WIDTH] = 0;

  fprintf(out, "\r\033[K[%s] ", bar);

  if (i == n)
    fprintf(out, "DONE!");
  else if (i != 0) {
    double elapsed = get_time() - args->start_time;
    uint64_t eta = (n - i) * (elapsed / i);

    uint64_t days = eta / (24 * 3600);
    eta -= 24 * 3600 * days;
    uint64_t hours = eta / 3600;
    eta -= 3600 * hours;
    uint64_t minutes = eta / 60;
    uint64_t seconds = eta - 60 * minutes;

    if (days != 0)
      fprintf(out, "ETA: %zud%02zu:%02zu:%02zu", days, hours, minutes, seconds);
    else if (hours != 0)
      fprintf(out, "ETA: %02zu:%02zu:%02zu", hours, minutes, seconds);
    else if (minutes != 0)
      fprintf(out, "ETA: %02zu:%02zu", minutes, seconds);
    else
      fprintf(out, "ETA: %zus", seconds);
  }

  args->wrote_progress = true;

  fflush(out);
  pthread_mutex_unlock(args->lock);
}

static void print_usage(const char *program_name, int status) {
  printf("Usage: %s [OPTIONS] OUTPUT_PATH\n", program_name);
  printf("  -h, --help      Display this message\n");
  printf("  --restore       Try to restore progress from the backup\n");
  printf("  --debug         Logs messages received from clients\n");
  printf("  --backup DIR    Store all progress made by the server to this "
         " directory\n");
  exit(status);
}

static void parse_args(int *argc, char **argv,
                       const char **output_path,
                       const char **backup_path,
                       bool *try_restore, bool *debug) {
  *output_path = *backup_path = NULL;
  *try_restore = false;
  *debug = false;

  for (int i = 1; i < *argc; ) {
    if (strcmp(argv[i], "--restore") == 0) {
      *try_restore = true;
      memmove(argv + i, argv + i + 1, ((*argc) - i - 1) * sizeof(*argv));
      (*argc)--;
    }
    if (strcmp(argv[i], "--debug") == 0) {
      *debug = true;
      memmove(argv + i, argv + i + 1, ((*argc) - i - 1) * sizeof(*argv));
      (*argc)--;
    }
    else if (strcmp(argv[i], "--backup") == 0) {
      if (i + 1 == *argc) print_usage(argv[0], 1);

      *backup_path = argv[i + 1];

      memmove(argv + i, argv + i + 2, ((*argc) - i - 2) * sizeof(*argv));
      (*argc) -= 2;
    }
    else if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) {
      print_usage(argv[0], 0);
    }
    else
      i++;
  }

  if (*argc >= 2)
    *output_path = argv[1];
}
